package com.hzc.gulimall.product.web;

import com.hzc.gulimall.product.entity.CategoryEntity;
import com.hzc.gulimall.product.service.CategoryService;
import com.hzc.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        //TODO 1.查出所有1级分类
        List<CategoryEntity> categoryEntityList = categoryService.getLevelOneCategories();
        //视图解析器进行拼串
        //classpath:/templates/ +返回值+  .html
        model.addAttribute("categorys", categoryEntityList);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> catelogJson = categoryService.getCatelogJson();
        return catelogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();//阻塞式等待，默认30s到期时间
        //锁会自动续期，每隔10s续期到30s。业务执行完成后，不会再续期。
        //最佳实践:
        //lock.lock(30,TimeUnit.SECONDS); 不会自动续期
        try {
            System.out.println("加锁成功，执行业务" + Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }
}
